import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import { routeList, homePath, notFoundPath } from './config'

type routeItemType = {
  path: string
  component: React.ComponentType<any>
  isLayout?: boolean
  redirect?: string
  children?: routeItemType[]
}

// 根据tree拼接路由路径并抹平嵌套关系
const handleRoutes = (routes: routeItemType[] = [], baseURL: string = '') => {
  const _routes = [...routes]
  const result: any = []

  const forArr = (list: routeItemType[] = [], pPath = baseURL) => {
    list.forEach((_: routeItemType, i: number) => {
      const { children, path, ...resProps } = _
      if (_.isLayout) {
        // (isLayout为true)时,保留嵌套关系(父子关系)
        let newResult: routeItemType[] = []
        if (children && children.length > 0) {
          children.forEach((child: routeItemType, index: number) => {
            const {
              children: subChildren,
              path: subPath,
              ...subResProps
            } = child
            if (subChildren && subChildren.length > 0) {
              newResult = newResult.concat(
                handleRoutes(subChildren, pPath + path + subPath),
              )
            }
            newResult.push({
              ...subResProps,
              path: pPath + path + subPath,
              // firstChild: Boolean(index === 0),
            })
          })
        }
        result.push({ ...resProps, children: newResult, path: pPath + path })
      } else {
        if (children && children.length > 0) {
          forArr(children, pPath + path)
        }
        result.push({ ...resProps, path: pPath + path })
      }
    })

    return result
  }

  return forArr(_routes)
}

const routeTree = handleRoutes(routeList)
console.log(routeTree)

// 渲染路由（包括嵌套、动态）
const renderRoutes = (routeTree: routeItemType[] = []) => {
  return routeTree.map((item: routeItemType) => {
    const { children, path, redirect } = item
    if (children && children.length > 0) {
      // console.log(item)
      return (
        <item.component key={path} path={path}>
          {/* {renderRoutes(children)} */}
          <Switch>
            {renderRoutes(children)}
            {/* 默认重定向到第一个子组件 */}
            <Redirect exact from={path} to={redirect || '/'} />
          </Switch>
        </item.component>
      )
    }
    return <Route key={path} exact path={path} component={item.component} />
  })
}

export default () => (
  <Switch>
    {renderRoutes(routeTree)}
    {/* 首屏页 */}
    <Redirect exact from="/" to={homePath} />
    <Redirect to={notFoundPath} />
  </Switch>
)
